package rgbos.forum.persistance;
  
import java.util.Vector;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import rgbos.forum.GUI.facade;
import rgbos.forum.domain.Auditor;
import rgbos.forum.domain.User;

public class XMLUser extends XMLUtil{
	private String userFileName_ = "users.xml";
	//user actions
	public boolean registerNewUser(User newUser){
		if (checkExistUser(newUser.getUsername())){
			Auditor.Log("The user " + newUser.getUsername() + " was Registered AllReady.", this.getClass());
    		return false;
		}
        //new User :
		Element root = getUserDoc_().getDocumentElement();
		Element nodePost = getUserDoc_().createElement("User");
		nodePost.setAttribute("UserName", newUser.getUsername());
		nodePost.setAttribute("PermmisionGroup", String.valueOf(REGULER));
		
		try {
			nodePost.setAttribute("Password" , facade.hashString(newUser.getPassword()));
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		nodePost.setAttribute("email", newUser.getEmail());
		root.appendChild(nodePost);
		Auditor.Log("The user " + newUser.getUsername() + " was added to the forum.", this.getClass());
		//modify counter :
		int tempCounter = Integer.valueOf(root.getAttribute("Counter"));
		root.setAttribute("Counter",String.valueOf(tempCounter+1));
		// writing the new XML to file
		XMLUtil.writeXMLFile(getUserDoc_(), userFileName_);
		return true;
	}
	public boolean logIn(String userName, String pass){
		if (!checkExistUser(userName)){
			Auditor.Log("The user " + userName + " was isn\'t registered.", this.getClass());
    		return false;
		}
	    String hashPass = null;
		try {
			hashPass = facade.hashString(pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
		NodeList nl = getUserDoc_().getElementsByTagName("User");
	    for (int i = 0; i < nl.getLength(); i++) {
	    	Node node = nl.item(i);
	    	NamedNodeMap nodeMap =  node.getAttributes();
	    	String tUsr = nodeMap.getNamedItem("UserName").getNodeValue(); // user name
	    	String tPass = nodeMap.getNamedItem("Password").getNodeValue();// password
	    	if (userName.equals(tUsr)){
	    		return hashPass.equals(tPass);
	    	}
	    }
		return false;
	}
	public boolean modifyUserDetails(User user){
		try {
			NodeList tempNl = getUserDoc_().getElementsByTagName("User");
			for (int i = 0; i < tempNl.getLength(); i++) {
				Node tempNode = tempNl.item(i);
				NamedNodeMap tempNMap = tempNode.getAttributes();
				String tUsr = tempNMap.getNamedItem("UserName").getNodeValue();
				if (tUsr.contentEquals(String.valueOf(user.getUsername()))){
					Element newChild = getUserDoc_().createElement("User");
					newChild.setAttribute("UserName", user.getUsername());
					newChild.setAttribute("PermmisionGroup", String.valueOf(user.getPermmisionGroup()));					
					try {
						newChild.setAttribute("Password" , facade.hashString(user.getPassword()));
					} catch (Exception e) {
						e.printStackTrace();
					}
					newChild.setAttribute("email", user.getEmail());
					
					tempNode.getParentNode().replaceChild(newChild, tempNode);
					Auditor.Log("The user " + user.getUsername() + " was modified.", this.getClass());
					XMLUtil.writeXMLFile(getUserDoc_(), userFileName_);
					return true;
				}
			}
		} catch (DOMException e) {
			return false;
		}
		Auditor.Log("The user " + user.getUsername() + " was not Registered.", this.getClass());
		return false;
	}
	public boolean deleteUser(String username){
		Element root = getUserDoc_().getDocumentElement();
		try {
			NodeList tempNl = getUserDoc_().getElementsByTagName("User");
			for (int i = 0; i < tempNl.getLength(); i++) {
				Node tempNode = tempNl.item(i);
				NamedNodeMap tempNMap = tempNode.getAttributes();
				String tUsr = tempNMap.getNamedItem("UserName").getNodeValue();
				if (tUsr.contentEquals(username)) {
					root.removeChild(tempNode);
					//modify counter :
					int tempCounter = Integer.valueOf(root.getAttribute("Counter"));
					root.setAttribute("Counter",String.valueOf(tempCounter-1));
					XMLUtil.writeXMLFile(getUserDoc_(), userFileName_);
					Auditor.Log("The user " + username + " was deleted from the forum.", this.getClass());
					return true;
				}
			}
		} catch (DOMException e) {
			return false;
		}
		Auditor.Log("The user " + username + " was not Registered.", this.getClass());
		return false;
	}
	
	//administrator actions
	public boolean setModerator(String username){
		if (!checkExistUser(username)){
			Auditor.Log("The user " + username +" isn\'t register", this.getClass());
			return false;
		}
		if (checkModerator(username)){
			Auditor.Log("The user " + username + " is all ready a moderator.", this.getClass());
			return false;
		}
    	if (changePermission(username,1)){
    		Auditor.Log(username + " is set to be a MODERATOR", this.getClass());
    		return true;
    	}
    	else {
    		Auditor.Log("The user " + username +" isn\'t register ", this.getClass());
    		return false;
    	}
		
	}
	//setting an admin user
	public boolean setAdmin(String username){
		if (!checkExistUser(username)){
			Auditor.Log("The user " + username +" isn\'t register", this.getClass());
			return false;
		}
		changePermission(username,2);
   		Auditor.Log("The user " + username +" is now Admin", this.getClass());
   		return true;
	}
	public boolean checkExistUser(String username) {
		NodeList nl = getUserDoc_().getElementsByTagName("User");
        for (int i = 0; i < nl.getLength(); i++) {
        	Node node = nl.item(i);
        	NamedNodeMap nodeMap =  node.getAttributes();
        	String tUsr = nodeMap.getNamedItem("UserName").getNodeValue(); // user name
        	if (tUsr.equals(username)){
        		return true;
        	}
        }
        return false;
	}
	public boolean changePermission(String username, int value) {
		String val = String.valueOf(value);
		NodeList nl = getUserDoc_().getElementsByTagName("User");
        for (int i = 0; i < nl.getLength(); i++) {
        	Node node = nl.item(i);
        	NamedNodeMap nodeMap =  node.getAttributes();
        	
        	String tUsr = nodeMap.getNamedItem("UserName").getNodeValue(); // user name
        	if (tUsr.equals(username)){
        		nodeMap.getNamedItem("PermmisionGroup").setNodeValue(val);
        		return true;
        	}
        }
        return false;
	}

	//Getters:
	public Vector<User> getUsers(){
		Vector<User> users = new Vector<User>();
		NodeList tempNl = getUserDoc_().getElementsByTagName("User");
		for (int i = 0; i < tempNl.getLength(); i++) {
			Node tempNode = tempNl.item(i);
			NamedNodeMap tempNMap = tempNode.getAttributes();
			
			String UserName = tempNMap.getNamedItem("UserName").getNodeValue();
			String Password = tempNMap.getNamedItem("Password").getNodeValue();
			String email = tempNMap.getNamedItem("email").getNodeValue();
			int PermmisionGroup = Integer.valueOf(tempNMap.getNamedItem("PermmisionGroup").getNodeValue());
			
			User tmpPost = new User(UserName, Password, email, PermmisionGroup);
			users.add(tmpPost);
		}
		return users;
	}
	
}
